<template>
  <div class="chapter-view-wrapper">
    <div class="chapter-header">
      <h3>章节管理</h3>
      <el-button type="primary" @click="showAddChapterDialog">
        <el-icon><Plus /></el-icon>新增章节
      </el-button>
    </div>
    
    <div v-if="chapters.length === 0" class="placeholder">
      <el-empty description="暂无章节内容" />
    </div>
    
    <div v-else class="chapter-list">
      <div v-for="chapter in chapters" :key="chapter.id" class="chapter-card">
        <div class="chapter-header-section">
          <div class="chapter-info">
            <span class="chapter-number">{{ chapter.sort }}</span>
            <h4 class="chapter-title">{{ chapter.title }}</h4>
            <span v-if="chapter.desc" class="chapter-desc">{{ chapter.desc }}</span>
          </div>
          <div class="chapter-actions">
            <el-button type="primary" size="small" @click="editChapter(chapter)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" @click="deleteChapter(chapter.id)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="chapter-content">
          <video-view :chapter_id="chapter.id" :course_id="course_id" />
        </div>
      </div>
    </div>
    
    <!-- 章节编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增章节' : '编辑章节'" width="500px">
      <el-form ref="chapterFormRef" :model="chapterForm" label-width="80px">
        <el-form-item label="章节序号" prop="sort">
          <el-input v-model="chapterForm.sort" type="number" placeholder="请输入章节序号" />
        </el-form-item>
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="chapterForm.title" placeholder="请输入章节标题" />
        </el-form-item>
        <el-form-item label="章节描述">
          <el-input v-model="chapterForm.description" type="textarea" placeholder="请输入章节描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitChapter">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, watch } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import VideoView from './VideoView.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 定义props
const props = defineProps({
  course_id: {
    type: Number,
    required: true
  }
})

// 响应式数据
const chapters = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const chapterFormRef = ref()
const chapterForm = ref({
  id: null,
  courseId: props.course_id,
  title: '',
  desc: '', 
})

// 获取章节列表
const getChapterList = async () => {
  try {
    // 确保参数名与后端一致，使用驼峰命名法
    const response = await request.get(`/course/chapter/list`, {
      params: { courseId: props.course_id }
    })
    if (response.code === 100) {
      chapters.value = response.data || []
      console.log('章节列表数据:', response)
    } else {
      ElMessage.error('获取章节列表失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取章节列表错误:', error)
    ElMessage.error('网络错误')
  }
}

// 显示新增章节对话框
const showAddChapterDialog = () => {
  dialogType.value = 'add'
  chapterForm.value = {
    id: null,
    courseId: props.course_id,
    title: '',
    description: '',
    sort: chapters.value.length > 0 ? Math.max(...chapters.value.map(c => c.sort)) + 1 : 1
  }
  dialogVisible.value = true
}

// 编辑章节
  const editChapter = (chapter) => {
    dialogType.value = 'edit'
    // 适配后端字段：desc -> description
    const formData = { ...chapter, courseId: props.course_id }
    if (formData.desc) {
      formData.description = formData.desc
      delete formData.desc
    }
    chapterForm.value = formData
    dialogVisible.value = true
  }

// 提交章节表单
  const submitChapter = async () => {
    try {
      let response
      const submitData = { ...chapterForm.value }
      // 适配后端字段：description -> desc
      if (submitData.description) {
        submitData.desc = submitData.description
        delete submitData.description
      }
      
      if (dialogType.value === 'add') {
        response = await request.post('/course/chapter/add', submitData)
      } else {
        response = await request.put('/course/chapter/update', submitData)
      }
    
    if (response.code === 100) {
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
      dialogVisible.value = false
      getChapterList()
    } else {
      ElMessage.error(response.message || (dialogType.value === 'add' ? '新增失败' : '更新失败'))
    }
  } catch (error) {
    ElMessage.error('网络错误')
  }
}

// 删除章节
const deleteChapter = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该章节吗？删除后章节下的所有视频也将被删除', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`/course/chapter/delete/${id}`)
    if (response.code === 100) {
      ElMessage.success('删除成功')
      getChapterList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      ElMessage.error('网络错误')
    }
  }
}

// 组件挂载时获取章节列表
onMounted(() => {
  console.log('ChapterView组件挂载，课程ID:', props.course_id)
  if (props.course_id) {
    getChapterList()
  }
})

// 监听课程ID变化，当切换课程时自动更新章节列表
watch(() => props.course_id, (newCourseId) => {
  console.log('课程ID变化，重新获取章节列表，新课程ID:', newCourseId)
  if (newCourseId) {
    // 更新表单中的课程ID
    chapterForm.value.courseId = newCourseId
    getChapterList()
  } else {
    // 如果课程ID为空，清空章节列表
    chapters.value = []
  }
}, { immediate: true })
</script>

<style scoped lang="scss">
.chapter-view-wrapper {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px 16px;
  
  .chapter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 0;
    
    h3 {
      margin: 0;
      color: #333;
    }
  }
  
  .chapter-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .chapter-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    background-color: #fff;
    overflow: hidden;
    
    .chapter-header-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      background-color: #f8f9fa;
      border-bottom: 1px solid #e0e0e0;
      
      .chapter-info {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .chapter-number {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 32px;
          height: 32px;
          background-color: #409eff;
          color: white;
          border-radius: 50%;
          font-weight: bold;
        }
        
        .chapter-title {
          margin: 0;
          font-size: 16px;
          color: #333;
        }
        
        .chapter-desc {
          color: #666;
          font-size: 14px;
        }
      }
      
      .chapter-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .chapter-content {
      padding: 16px;
    }
  }
  
  .placeholder {
    padding-top: 60px;
    text-align: center;
  }
}
</style>